import {EyeOutlined, PlusOutlined, TableOutlined} from '@ant-design/icons';
import type { ActionType, ProColumns, ProFormInstance } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Alert, Button, Card, Empty, Form, Image, Space, message } from 'antd';
import React, { useRef, useState } from 'react';
import type { TableListItem, TableListPagination } from './data';
import { addFormData, removeFormData, page, formField, getForms, updateFormData } from './service';
import { useRequest, useSearchParams } from "@@/exports";
import { BetaSchemaForm } from '@ant-design/pro-components';
import { history } from '@umijs/max'
import './index.less'
import CustomImgUpload from '@/components/CustomImgUpload';
import CustomFileUpload from '@/components/CustomFileUpload';

/**
 * 添加节点
 *
 * @param formId
 * @param value
 */

const handleAdd = async (formId: any, value: string) => {
  const hide = message.loading('正在添加');

  try {
    await addFormData({
      formType: formId,
      value: value
    })
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param dataId
 * @param formId
 * @param value
 */

const handleUpdate = async (dataId: any, formId: any, value: string) => {
  const hide = message.loading('正在编辑');

  try {
    await updateFormData({
      id: dataId,
      formType: formId,
      value: value
    });
    hide();
    message.success('编辑成功');
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeFormData({
      idList: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  const [searchParams, setSearchParams] = useSearchParams();
  const formId = searchParams.get('formId');
  const { data = [], loading: fieldLoading } = useRequest(() => {
    return formField({
      formId: formId,
    });
  }, { refreshDeps: [formId], ready: !!formId });

  // console.log('data', data);

  const fileKeyMapRef = useRef<any>({})
  const imgKeyMapRef = useRef({})
  const [editForm] = Form.useForm()

  const cols = data?.map((item: any, index: number) => {
    const newItem: any = {
      title: item.property,
      dataIndex: item.name,
      key: item.name,
      valueType: item.inputType,
      hideInSearch: true,
    }
    if(index === 0) {
      newItem.fixed = 'left';
    }
    if (item.inputType === 'imageUpload') {
      newItem.width = 100
      newItem.renderFormItem = () => {
        return <CustomImgUpload  />
      }
      newItem.render = (text: any, record: any) => {
        return record?.[item.name]?.url ? <Image width={50} preview={{
          mask: <EyeOutlined />
        }} src={record?.[item.name]?.url} /> : '-'
      }
    }
    if (item.inputType === 'fileUpload') {
      newItem.width = 300
      newItem.renderFormItem = () => {
        return <CustomFileUpload  />
      }
      newItem.render = (text: any, record: any) => {
        return record?.[item.name] ? <Space wrap>
          {record?.[item.name]?.map((it: any, index: number) => {
            return <div key={it?.url + index}>
              <a href={it?.url}>{it?.name}</a>
            </div>
          })}
        </Space> : '-'
      }
    }
    return newItem
  }) || []

  const columns: ProColumns<any>[] = [
    {
      title: '表单名称',
      dataIndex: 'formId',
      hideInForm: true,
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        showSearch: true,
        // allowClear: false,
        onChange(val: any) {
          setSearchParams({
            formId: val || ''
          })
          actionRef.current?.reloadAndRest?.()
        }
      },
      initialValue: formId === null ? undefined : Number(formId),
      async request({ keyWords }) {
        const forms = await getForms({
          formId: formId,
          page: 0,
          size: 10,
          keyWords
        });
        return forms.data?.current_data?.map((item: any) => ({
          ...item,
          label: item?.name,
          value: item?.id
        }))
      },
    },
    {
      title: '关键词',
      dataIndex: 'keyword',
      hideInForm: true,
      hideInTable: true,
      hideInSearch: !formId,
      valueType: 'input',
    },
    ...(cols || []),
  ];

  if (cols?.length) {
    columns.push({
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 80,
      render: (_, record) => {
        return <BetaSchemaForm<any>
          key="edit"
          layoutType={'ModalForm'}
          // initialValues={record}
          form={editForm}
          onFinish={async (values) => {
            Object.keys(values).forEach(key => {
              // console.log(imgKeyMapRef.current[key]);

              if (imgKeyMapRef.current[key]) {
                values[key] = imgKeyMapRef.current[key]
              }
              if (fileKeyMapRef.current[key]) {
                values[key] = fileKeyMapRef.current[key]
              }
            })
            // console.log(fileKeyMapRef, values);


            const isOk = await handleUpdate(record?.key, formId, JSON.stringify(values))
            if (isOk) {
              actionRef.current?.reload()
            }
            return isOk
          }}
          modalProps={{
            destroyOnClose: true,
            title: "编辑",
            width: "500px",
            onCancel() {
            }
          }}
          trigger={<a onClick={() => {
            editForm.setFieldsValue(record)
          }}>编辑</a>}
          columns={cols}
        />
      },
    })
  }

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="业务数据维护表格"
        loading={fieldLoading}
        actionRef={actionRef}
        rowKey="key"
        formRef={formRef}
        scroll={{x: 'max-content'}}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => formId ? [
          <Button icon={<TableOutlined/>} key={'design'} onClick={() => {
            history.push(`/dynamic-form/design-form?formId=${formId}`)
          }}>表设计</Button>,
          <BetaSchemaForm<any>
            key="primary"
            className='add_modal_form'
            layoutType={'ModalForm'}
            onFinish={async (values) => {
              // console.log(values, imgKeyMapRef);

              Object.keys(values).forEach(key => {
                // console.log(imgKeyMapRef.current[key]);

                if (imgKeyMapRef.current[key]) {
                  values[key] = imgKeyMapRef.current[key]
                }
                if (fileKeyMapRef.current[key]) {
                  values[key] = fileKeyMapRef.current[key]
                }
              })
              // console.log(values);

              const isOk = await handleAdd(formId, JSON.stringify(values))
              if (isOk) {
                actionRef.current?.reload()
              }
              return isOk
            }}
            // layout='horizontal'
            style={{
              // maxWidth: 'none',
              // padding: 24,
              // display: 'flex',
              // flexWrap: 'wrap',
              // gap: 20
            }}
            modalProps={{
              destroyOnClose: true,
              title: "新增数据",
              width: 500,
            }}
            trigger={<Button type="primary" onClick={() => {
            }}>
              <PlusOutlined /> 新建
            </Button>}
            columns={cols}
          />,
        ] : []}
        request={async ({ pageSize, current, keyword }) => {
          const res = await page({
            size: pageSize,
            page: current,
            formId: formId,
            keyword,
          });
          const list = res.data?.current_data;
          const dataList: any[] = []
          list?.forEach((item: any) => {
            try {
              const valObj = JSON.parse(item?.value);
              dataList.push({
                ...valObj,
                key: item?.id
              });
            } catch (e) {

            }
          })
          // console.log(dataList)
          return {
            data: formId ? dataList : []
          }
        }}
        onReset={() => {
          setSearchParams({
            formId: ''
          })
          formRef.current?.setFieldsValue({
            formId: null
          })
        }}
        columns={columns}
        rowSelection={cols?.length ? {
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        } : undefined}
        tableRender={({ }, defaultDom) => {
          if (formId && !cols?.length) {
            return <Card>
              <Empty description={<Space>
                <span>该表单下没有关联的字段信息</span>
                <a onClick={() => {
                  history.push(`/dynamic-form/design-form?formId=${formId}`)
                }}>去关联?</a>
              </Space>} />
            </Card>
          }
          if (!formId && !cols?.length) {
            return <Alert showIcon message="请选择表单" type="warning" />
          }
          return defaultDom
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            danger
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          {/*<Button type="primary">批量审批</Button>*/}
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
